<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>导航守卫</title>
</head>
<body>
<div id="app">
    <router-link to="/">首页</router-link>
    <router-link to="/user">用户列表</router-link>
    <router-link to="/article">帖子列表</router-link>
    <router-link to="/login">登录</router-link>
    <router-link to="/about">关于</router-link>
    <router-view></router-view>
</div>

<script type="module">
    import {createApp} from "../../../../js/vue.esm-browser.js";
    import {createRouter, createWebHashHistory} from "../../../../js/vue-router.esm-browser.js";

    const Home = {template: "<h1>首页</h1>"}
    const User = {template: "<div><ul><li>用户列表</li></ul></div>"}
    const Article = {template: "<div><ul><li>帖子列表</li></ul></div>"}
    const Login = {template: "<h1>登录</h1>"}
    const About = {template: "<h1>关于我们</h1>"}


    const routes = [
        {
            path: "/",
            component: Home,
        },
        {
            path: "/user",
            component: User,
        },
        {
            path: "/article",
            component: Article,
        },
        {
            path: "/login",
            component: Login,
        },
        {
            path: "/about",
            component: About,
        },
    ]

    let router = createRouter(
        {
            history: createWebHashHistory(),
            routes,
        }
    );

    router.beforeEach(function (to, from, next) {
        // false 表示未登录状态
        let isLogin = false
        // let isLogin = true
        // 在未登录状态并且目标 url 为 /user，跳转到 登录页面
        if (!isLogin && to.path == "/user") {
            next('/login')
        }
        // 在未登录状态并且目标 url 为 /article，跳转到 登录页面
        if (!isLogin && to.path == "/article") {
            next('/login')
        }
        next()
    })

    router.afterEach(function (to, from) {
        console.log("to", to)
        console.log("from", from)
    })

    let app = createApp(
        {
            setup() {
                return {}
            }
        }
    )
    app.use(router)
    app.mount("#app")
</script>
</body>
</html>